package com.wrs.wrsfcmpush

import android.Manifest
import android.annotation.TargetApi
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.telecom.PhoneAccount
import android.telecom.PhoneAccountHandle
import android.telecom.TelecomManager
import android.telecom.VideoProfile
import android.widget.Button
import android.widget.EditText
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import com.wrs.wrsfcmpush.service.MyAccessibilityService
import com.wrs.wrsfcmpush.service.MyConnectionService
import com.wrs.wrsfcmpush.utils.InComeCallMgr
import com.wrs.wrsfcmpush.utils.InComingHandle


//https://developer.android.google.cn/develop/connectivity/telecom/dialer-app?hl=zh-cn#incoming-calls
//https://developer.android.google.cn/develop/connectivity/telecom/selfManaged?hl=en#connectionImplementation
//https://developer.android.google.cn/develop/connectivity/telecom/voip-app/telecom?hl=en#answer_a_call

//https://zhuanlan.zhihu.com/p/385579708
//https://blog.csdn.net/qq_27122177/article/details/136659140
class MainActivity : ComponentActivity() {
    var TAG: String = "MainActivity"
    private lateinit var phoneExt: EditText
    private lateinit var btn: Button

   lateinit  var telecomManager: TelecomManager

//   var phoneAccountHandle:PhoneAccountHandle? = null
//    var number = "18820406059"

    lateinit  var phoneAccountHandle:PhoneAccountHandle
    var number = "19075095013"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

//        InComeCallMgr.handle = object : InComingHandle{
//            override fun inComing() {
////                startIncomingCall()
////                TaskUtils.launchApp("")
//            }
//
//        }

        phoneExt = findViewById(R.id.et_ext)
        phoneExt.setText(this.number)

        btn = findViewById(R.id.btn)
        btn.setOnClickListener {
//            number = phoneExt.text.toString()
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                startOutgoingCall()
//            }
        }

        findViewById<Button>(R.id.noZhangaiBtn).setOnClickListener {
            noZhangaiBtnClick()
        }
        findViewById<Button>(R.id.inComeBtn).setOnClickListener {
            inComeBtnClick()
        }
        findViewById<Button>(R.id.settingBtn).setOnClickListener {
            settingBtnClick()
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            initVoip()
        }
        val PERMISSION_REQUEST_CODE = 1
        val PERMISSION_STORAGE = android.Manifest.permission.CALL_PHONE

        checkAndRequestPermissions(PERMISSION_STORAGE, PERMISSION_REQUEST_CODE)


//        val intent = Intent(this, KeepServices::class.java)
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(intent);
//        } else {
//            startService(intent);
//        }

        // 无障碍服务
        val myAccessibilityServiceIntent = Intent(this, MyAccessibilityService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(myAccessibilityServiceIntent);
        } else {
            startService(myAccessibilityServiceIntent);
        }

//        SettingUtils.enterWhiteListSetting(this)
//        if (!OpenAccessibilitySettingHelper.isAccessibilitySettingsOn(
//                this,
//                MyAccessibilityService::class.java.getName()
//            )
//        ) { // 判断服务是否开启
////            OpenAccessibilitySettingHelper.jumpToSettingPage(this) // 跳转到开启页面
//        } else {
////            ToastUtil.showShortToast(this, "服务已开启")
//            //do other things...
//        }

//        HooliganActivity.startHooligan(this)
    }
    fun  settingBtnClick() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", packageName, null)
        intent.setData(uri)
        startActivity(intent)
    }

    fun  inComeBtnClick() {
        startIncomingCall()
    }

    fun noZhangaiBtnClick() {
                val accessIntent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        startActivity(accessIntent)
    }

    fun  inComing() {
        val telecomManager = this.getSystemService(TELECOM_SERVICE) as TelecomManager
        val extras = Bundle()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            telecomManager.addNewIncomingCall(phoneAccountHandle, extras)
        }
    }


    @RequiresApi(Build.VERSION_CODES.M)
    fun test() {

        startOutgoingCall()
    }
    fun checkAndRequestPermissions(permission: String, requestCode: Int) {
        val permissions = mutableListOf<String>()

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            permissions.add(Manifest.permission.MANAGE_OWN_CALLS)
//        }
//        permissions.add(Manifest.permission.CALL_PHONE)

        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        permissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)

//        permissions.add(Manifest.permission.ANSWER_PHONE_CALLS)
//        permissions.add(Manifest.permission.READ_PHONE_NUMBERS)


        permissions.add(Manifest.permission.BIND_ACCESSIBILITY_SERVICE)
        permissions.add(Manifest.permission.FOREGROUND_SERVICE)
        // To show call notifications we need permissions since Android 13

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.POST_NOTIFICATIONS)
        }
         ActivityCompat.requestPermissions(this, permissions.toTypedArray(), requestCode)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    fun  initVoip() {
        telecomManager = this.getSystemService(Context.TELECOM_SERVICE) as TelecomManager


        val componentName =  ComponentName(this, MyConnectionService::class.java)
        val phoneAccountId = packageName;
        phoneAccountHandle = PhoneAccountHandle(componentName, "App name")

        var phoneAccount = telecomManager.getPhoneAccount(phoneAccountHandle)
        if (phoneAccount == null) {
            var capabilities = PhoneAccount.CAPABILITY_CALL_PROVIDER
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                capabilities = PhoneAccount.CAPABILITY_SELF_MANAGED
            }

            var url = Uri.parse("tel:$number")
             phoneAccount = PhoneAccount.builder(phoneAccountHandle, "Admin")
                .setCapabilities(capabilities)
                .setAddress(url)
                .setSubscriptionAddress(url)
                .setCapabilities(capabilities) //必须
                .build()
        }
        telecomManager.registerPhoneAccount(phoneAccount); // 确保有适当的电话账户

        if (!phoneAccount.isEnabled()) {
            telecomManager.registerPhoneAccount(phoneAccount)
        }
    }



    @TargetApi(Build.VERSION_CODES.M)
    fun startOutgoingCall() {
        if (phoneAccountHandle == null) {
            initVoip()
        }
        val extras = Bundle()
        extras.putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, true)

        val manager = this.getSystemService(TELECOM_SERVICE) as TelecomManager
        val phoneAccountHandle = PhoneAccountHandle(ComponentName(packageName, MyConnectionService::class.java!!.getName()), "estosConnectionServiceId")
        val test = Bundle()
        test.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle)
        test.putInt(TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, VideoProfile.STATE_BIDIRECTIONAL)
        test.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, extras)
        try {
            manager.placeCall(Uri.parse("tel:$number"), test)
        } catch (e:SecurityException){
            e.printStackTrace()
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    fun  startIncomingCall(){

        if (this.checkSelfPermission(android.Manifest.permission.MANAGE_OWN_CALLS) == PackageManager.PERMISSION_GRANTED) {
            val extras = Bundle()
            val uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null)
            extras.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS, uri)
            extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle)
//            extras.putParcelable(TelecomManager.EXTRA_PHONE_NUMBER, phoneAccountHandle);
            extras.putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, true)
            val isCallPermitted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                telecomManager.isIncomingCallPermitted(phoneAccountHandle)
            } else {
                true
            }

            telecomManager.addNewIncomingCall(phoneAccountHandle, extras)
        }
    }

@RequiresApi(Build.VERSION_CODES.M)
fun  ss() {
    var context = this
  var  telecomManager = context.getSystemService(TELECOM_SERVICE) as TelecomManager
    val phoneAccountId: String = context.getPackageName()
    val componentName: ComponentName = ComponentName(context, MyConnectionService::class.java)
   var phoneAccountHandle = PhoneAccountHandle(componentName, phoneAccountId)
    var phoneAccount = telecomManager.getPhoneAccount(phoneAccountHandle)
    if (phoneAccount == null) {
        val uri = Uri.parse("tel:987654321")
        // 使用CAPABILITY_CALL_PROVIDER等类型的PhoneCount需要跳转到通话账号打开权限
        var capabilities = PhoneAccount.CAPABILITY_CALL_PROVIDER
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            capabilities = PhoneAccount.CAPABILITY_SELF_MANAGED
        }
       var  phoneAccount = PhoneAccount
            .builder(phoneAccountHandle, "voip 电话")
            .setAddress(uri)
            .setSubscriptionAddress(uri)
            .setCapabilities(capabilities) //必须
            .build()
    }
    if (!phoneAccount.isEnabled()) {
        telecomManager.registerPhoneAccount(phoneAccount)
    }
}


//    fun displayNewIncomingCall(rongCallSession: RongCallSession) {
//        if (!isPhoneAccountEnable()) {
//            return
//        }
//        //传递一些必要的信息
//        val inviterUserId: String = rongCallSession.getInviterUserId()
//        val userInfo: UserInfo = RongUserInfoManager.getInstance().getUserInfo(inviterUserId)
//        var userName = inviterUserId
//        if (userInfo != null) {
//            userName = userInfo.getName()
//        }
//        val extras = Bundle()
//        val uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, inviterUserId, null)
//        extras.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS, uri)
//        extras.putString(EXTRA_CALLER_NAME, userName)
//        extras.putString(EXTRA_CALL_UUID, rongCallSession.getCallId())
//
//
//        //调用addNewIncomingCall添加来电
//        telecomManager.addNewIncomingCall(phoneAccountHandle, extras)
//    }
//
//
//    fun startCall(uuid: String?, number: String?, callerName: String?) {
////        if (!isPhoneAccountEnable()) {
////            return
////        }
//        //传递一些必要的信息
//        val extras = Bundle()
//        val uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null)
//        val callExtras = Bundle()
//        callExtras.putString(EXTRA_CALLER_NAME, callerName)
//        callExtras.putString(EXTRA_CALL_UUID, uuid)
//        callExtras.putString(EXTRA_CALL_NUMBER, number)
//        extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, handle)
//        extras.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, callExtras)
//
//        //调用addNewIncomingCall添加去电
//        telecomManager.placeCall(uri, extras)
//    }

}
